from dataclasses import dataclass, field
from typing import Any, Union, Generator

from flask import jsonify, stream_with_context, Response as FlaskResponse

from .http_code import HttpCode


@dataclass
class Response:
    """基础HTTP相应格式"""

    code: HttpCode = HttpCode.SUCCESS
    message: str = ""
    data: Any = field(default_factory=dict)


def json(data: Response = None):
    """基础相应"""
    return jsonify(data), 200


def success_json(data: Any = None):
    """ "成功数据响应"""
    return json(Response(code=HttpCode.SUCCESS, message="", data=data))


def fail_json(data: Any = None):
    """ "失败数据响应"""
    return json(Response(code=HttpCode.FAIL, message="", data=data))


def validate_error_json(erros: dict = None):
    """数据错误验证响应"""

    key = next(iter(erros))
    if key is not None:
        msg = erros.get(key)[0]
    return json(Response(code=HttpCode.VALIDATA_ERROR, message=msg, data=""))


def message(code: HttpCode, message: str = ""):
    """基础消息响应"""
    return json(Response(code=code, message=message, data={}))


def success_message(msg: str = ""):
    """ "成功消息响应"""
    return message(code=HttpCode.SUCCESS, message=msg)


def fail_message(msg: str = ""):
    """失败消息响应"""
    return message(code=HttpCode.FAIL, message=msg)


def not_found_message(msg: str = ""):
    """未找到消息响应"""
    return message(code=HttpCode.NOTE_FOUND, message=msg)


def unauthorized_message(msg: str = ""):
    """未授权消息响应"""
    return message(code=HttpCode.NOTE_FOUND, message=msg)


def forbidden_message(msg: str = ""):
    """ "无权限消息响应"""
    return message(code=HttpCode.FORBIDDEN, message=msg)


def compact_generate_response(response: Union[Response, Generator]) -> FlaskResponse:
    if isinstance(response, Response):
        return json(response)
    else:
        def generate() -> Generator:
            yield from response

        return FlaskResponse(
            stream_with_context(generate()),
            status=200,
            mimetype="text/event-stream",
        )
